package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gulimall.gulimallthirdparty.util.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.excption.PhoneExistException;
import com.atguigu.gulimall.member.excption.UsenameExistException;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.MemberUserLoginVo;
import com.atguigu.gulimall.member.vo.SocilaUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.web.bind.annotation.RequestBody;
import sun.nio.cs.ext.MacArabic;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        MemberDao memberDao = this.baseMapper;

        //设置默认等级
        MemberLevelEntity level = memberLevelDao.getDefaultLevel();
        entity.setLevelId(level.getId());

        //设置其他默认信息
        //检查唯一性 为了让Controller感知异常，用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserUnique(vo.getUserName());

        //加密存储 盐值加密，$1$+8位字符
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);


        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());

        //设置创建时间
        entity.setCreateTime(new Date());

        memberDao.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer mobie = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobie > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserUnique(String username) throws UsenameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsenameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberUserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //去数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity == null) {
            //没有这个信息登录失败
            return null;
        } else {
            //获取到数据库中的密码字段
            String sqlPassword = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //明文密码，和数据库的盐值密码
            boolean matches = passwordEncoder.matches(password, sqlPassword);
            if (matches) {
                //登录成功
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocilaUser socilaUser) throws Exception {
        //登录注册合并逻辑
        String uid = socilaUser.getUid();
        //是否已经登录过系统，注册过吗 用uid判断
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>()
                .eq("social_uid", uid));
        if (memberEntity!=null){
            //有用户 换令牌信息
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socilaUser.getAccess_token());
            update.setExpiresIn(socilaUser.getExpires_in());

            memberDao.updateById(update);
            memberEntity.setAccessToken(socilaUser.getAccess_token());
            memberEntity.setExpiresIn(socilaUser.getExpires_in());
            return memberEntity;
        }else {
            //2.没有查到当前社交用户对应的记录，需要注册一个
            MemberEntity regist = new MemberEntity();
            //查询当前社交账号信息，昵称 性别 等
           try {
               Map<String,String> query = new HashMap<>();
               query.put("access_token",socilaUser.getAccess_token());
               query.put("uid",socilaUser.getUid());
               HttpResponse response = HttpUtils.doGet("http://api.weibo.com", "/users/show.json", "get", new HashMap<String, String>(),
                       query);
               if (response.getStatusLine().getStatusCode()==200){
                   String json = EntityUtils.toString(response.getEntity());
                   JSONObject jsonObject = JSONObject.parseObject(json);
                   //对应昵称
                   String name = jsonObject.getString("name");
                   String sex = jsonObject.getString("gender");
                   regist.setNickname(name);
                   regist.setGender("m".equals(sex)?1:0);
               }
           }catch (Exception e){}
            regist.setSocialUid(socilaUser.getUid());
            regist.setAccessToken(socilaUser.getAccess_token());
            regist.setExpiresIn(socilaUser.getExpires_in());
            memberDao.insert(regist);
            return regist;
        }
    }

}